import 'package:cloud_medicine/http/comment_api.dart';
import 'package:cloud_medicine/http/config.dart';
import 'package:cloud_medicine/http/post_api.dart';
import 'package:flutter/material.dart';

// 点赞/取消点赞显示组件
class FavoriteIcon extends StatefulWidget {
  final bool isLike;
  final String like_num;
  final int id; // 评论或帖子ID
  final bool isPost; // 是否为帖子

  FavoriteIcon({
    Key key,
    @required this.isLike,
    @required this.like_num,
    @required this.id,
    @required this.isPost,
  }) : super(key: key);

  @override
  _FavoriteIconState createState() => _FavoriteIconState();
}

class _FavoriteIconState extends State<FavoriteIcon> {
  bool isLike = false;
  String like_num = "0";

  @override
  void initState() {
    super.initState();
    setState(() {
      isLike = widget.isLike;
      like_num = widget.like_num;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: <Widget>[
        GestureDetector(
          child: Icon(
            isLike ? Icons.favorite : Icons.favorite_border,
            color: isLike ? Colors.red : Colors.grey,
          ),
          onTap: () async {
            // TODO: 需要向后端发送点赞/取消点赞
            if(widget.isPost) {
              await alterLikeStatus_api('$backIP/post/like', {
                'post_id':widget.id
              });
            }else{
              await likeComment_api('$backIP/comment/like', {
                'comment_id': widget.id,
              });
            }
            setState(() {
              if (isLike) {
                like_num = (int.parse(like_num) - 1).toString();
              } else {
                like_num = (int.parse(like_num) + 1).toString();
              }
              isLike = !isLike;
            });
//            widget.callback();
          },
        ),
        Text(
          like_num,
          style: TextStyle(color: isLike ? Colors.red : Colors.grey),
        )
      ],
    );
  }
}
